package com.andova.camerax

import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.CameraSelector
import androidx.camera.core.CameraSelector.LENS_FACING_FRONT
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageCapture
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import com.andova.camerax.databinding.ActivityMainBinding
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

class MainActivity : AppCompatActivity() {
    private val mPlane = ImagePlane()
    private var mExecutor: ExecutorService? = null
    private var mBinding: ActivityMainBinding? = null
    private var cameraProvider: ProcessCameraProvider? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(mBinding?.root)
    }

    override fun onResume() {
        super.onResume()
        mExecutor = Executors.newSingleThreadExecutor()
        cameraProvider = ProcessCameraProvider.getInstance(this).get()
        cameraProvider?.bindToLifecycle(
                this,
                CameraSelector.Builder().requireLensFacing(LENS_FACING_FRONT).build(),
                Preview.Builder().build().apply {
                    setSurfaceProvider(mBinding?.preview?.surfaceProvider)
                },
                ImageCapture.Builder().build(),
                ImageAnalysis.Builder().setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST).build().apply {
                    setAnalyzer(mExecutor!!) {
                        val nv21 = mPlane.YUVToNV21(it.image)
                        println("imageProxy -> ${nv21?.size}")
                        it.close()
                    }
                }
        )
    }

    override fun onPause() {
        super.onPause()
        mExecutor?.shutdown()
        cameraProvider?.unbindAll()
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (!hasFocus) return
        window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_FULLSCREEN
                or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
    }
}
